from django.core.management.base import BaseCommand
from core.models import SiteInfo
import os
from django.core.files import File
from django.conf import settings
import sys

sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(__file__)))))
from generate_logo import generate_logo

class Command(BaseCommand):
    help = '生成新Logo并更新网站设置中的Logo'

    def handle(self, *args, **kwargs):
        try:
            # 调用Logo生成函数
            logo_path = generate_logo()
            self.stdout.write(self.style.SUCCESS(f'成功生成Logo: {logo_path}'))
            
            # 获取网站信息
            site_info = SiteInfo.get_site_info()
            
            # 如果已有Logo，先记录原路径便于后续删除
            old_logo = None
            if site_info.logo:
                old_logo = site_info.logo.path
            
            # 使用新生成的Logo更新网站设置
            with open(logo_path, 'rb') as f:
                site_info.logo.save('cursor_rules_logo.png', File(f), save=True)
                
            # 保存更改    
            site_info.save()
            
            # 如果有旧Logo且不是当前使用的，可以删除
            if old_logo and old_logo != site_info.logo.path and os.path.exists(old_logo):
                os.remove(old_logo)
                self.stdout.write(self.style.SUCCESS(f'删除旧Logo: {old_logo}'))
            
            self.stdout.write(self.style.SUCCESS('成功更新网站Logo'))
            
        except Exception as e:
            self.stdout.write(self.style.ERROR(f'更新Logo时出错: {e}')) 